﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Mysoft.Utility
{
    public static class FileHelper
    {
        public static void WriteFile(string path, string text)
        {
            var encoding = EncodingType.GetEncoding(path);
            using (StreamWriter m_streamWriter = new StreamWriter(path, false, encoding))
            {
                // 使用StreamWriter来往文件中写入内容
                m_streamWriter.BaseStream.Seek(0, SeekOrigin.Begin);

                m_streamWriter.Write(text);

                //关闭此文件
                m_streamWriter.Flush();
                m_streamWriter.Close();
            }
        }

        /// <summary>
        /// 获取txt文件中的数据
        /// </summary>
        public static string GetTxt(string filePath, Encoding encode = null)
        {
            if (encode == null)
            {
                encode = Encoding.Default;
            }
            List<string> exList = new List<string>();
            return System.IO.File.ReadAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory + filePath), encode);
        }


        public static void DelFile(string filePath)
        {
            if (File.Exists(filePath) == false)
            {
                return;
            }
            File.Delete(filePath);
        }

        public static void WriteLog(string name, string content, string filePath = "")
        {
            if (string.IsNullOrEmpty(filePath) == true)
            {
                filePath = AppDomain.CurrentDomain.BaseDirectory + "\\log\\" + name + "log.txt";
            }
            DelFile(filePath);
            FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write);
            //设定书写的开始位置为文件的末尾 
            fs.Position = fs.Length;
            Encoding encoder = Encoding.UTF8;
            byte[] bytes = encoder.GetBytes(content);
            //将待写入内容追加到文件末尾 
            fs.Write(bytes, 0, bytes.Length);
            fs.Close();
        }
    }
}
